// pages/goods/goods.js
import { getGoodsListApi } from "../../api/goods";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    limit: 10,
    category2Id: "",
    totalPages: 0,
    goodsList: [],
    isRefreshing: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options);
    this.data.category2Id = options.category2Id || "";
    this.data.category1Id = options.category1Id || "";
    this.getGoodsList();
  },

  async getGoodsList() {
    const { page, limit, category2Id, category1Id } = this.data;
    const res = await getGoodsListApi({
      page,
      limit,
      category2Id,
      category1Id,
    });

    let goodsList = res.records;

    if (page > 1) {
      // 追加数据
      goodsList = [...this.data.goodsList, ...goodsList];
    }

    this.setData({
      goodsList,
      totalPages: res.pages,
    });
  },

  // 下拉刷新
  async handlePullDownRefresh() {
    this.data.page = 1;
    await this.getGoodsList();
    this.setData({
      isRefreshing: false,
    });
    wx.showToast({
      title: "更新数据成功",
      icon: "success",
    });
  },

  // 上拉加载
  async handlePullUpLoading() {
    if (this.data.page >= this.data.totalPages) return;
    // 没有setData和page相关的页面的位置不会重新渲染
    this.setData({
      page: this.data.page + 1,
    });
    await this.getGoodsList();
  },

  goBack() {
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
